(function (window, $, undefined) {
  /* global Cookies, sha256 */

  var userName = '$_userName_admin'; // 记住用户名的字段名
  var expires = 30; // 记住用户名的有效期，单位为天

  var textLock = '已超过最大出错限制次数，请 30 分钟后再试';

  // 出错限制最大次数
  var MAX_ERROR = Infinity;

  // 页面表单元素
  var $form = $('#form');
  // 记住用户名相关的勾选元素
  var $check = $('.checkbox input')[0];

  // 如果浏览器记住了用户名，则自动输入
  var _name = Cookies.get(userName);
  if (_name) {
    $('#username').val(_name);
    if ($check) { // 防止因为某些原因，界面上取消了该功能，元素不能获取到
      $check.checked = true;
    }
  }

  // 表单验证规则设置
  var $validate = $form.validate({
    rules: {
      username: {required: true, maxlength: 30},
      password: { /*isPassword: true,*/ required: true},
      vcode: {required: true},
      vpassword: {required: true}
    },
    messages: {
      username: { required: '用户名不能为空', maxlength: '请输入1-30个字符' },
      password: { required: '密码不能为空' },
      vcode: {required: '验证码不能为空'},
      vpassword: {required: '认证码不能为空'}
    },
    errorPlacement: function (error, element) {    // 错误信息位置设置方法
      error.appendTo(element.parent()); // 这里的element是录入数据的对象
    }
  });

  // 表单回车键快捷操作
  $form.on('keydown', function (e) {
    if (e.keyCode === 13) {
      $('#loginBtn').trigger('click.login');
    }
  });

  var sha666 = function (str) {
    var ret = sha256(str);
    return ret.substr(0, 16) + ret.substr(20, 63) + '666';
  };

  window.sha666 = sha666

  function checkLoginLock() { return;
    if (localStorage.LOGIN_LOCK) {
      var lockTime = +localStorage.LOGIN_LOCK;
      var now = Date.now();
      if (now - lockTime < 30 * 60 * 1000) {
        $('#errorMsg').text(textLock);
        return true;
      } else {
        clearLock();
      }
    }
  }
  checkLoginLock();

  function clearLock() {
    localStorage.removeItem('LOGIN_LOCK');
    localStorage.removeItem('CUR_ERROR');
  }

  // 发送短信验证码
  var $vcode = $('#send-vcode');
  $vcode.click(function () {
    var name = $('#username').val();
    var isBan = $vcode.hasClass('ban');
    if (isBan) {
      return;
    }
    if (name) {
      $.ajax(ajaxURL.SYSTEM + '/sys/user/code', {
        type: 'GET',
        xhrFields: {
          withCredentials: true
        },
        crossDomain: true,
        data: {
          account: name,
          type: 1
        },
        success: function (res) {
          if (res.code === 0 || res.code === '0' || res.code === '200') {
            layer.msg(res.msg || '验证码发送成功', {
              icon: 6
            });

            $('#send-vcode').addClass('ban').text('60 s');

            var cd = 60;
            var tmr = setInterval(function () {
              cd--;
              if (cd < 1) {
                clearInterval(tmr);
                $('#send-vcode').removeClass('ban').text('重新发送');
              } else {
                $('#send-vcode').text(cd + ' s');
              }
            }, 1000);

          } else {
            layer.msg('验证码发送失败', {
              icon: 0
            })
          }
        },
        error: function (xhr) {
          layer.msg('验证码发送失败', {
            icon: 0
          })
        }
      })
    } else {
      layer.msg('请先输入用户名', {
        icon: 0
      })
    }
  });

  // 登录操作
  $('#loginBtn').on('click.login', function () {

    if (checkLoginLock()) {
      return false;
    }

    $('#errorMsg').text('');

    // 验证表单
    if (!$validate.form()) {
      return false;
    }

    var name = $('#username').val();
    var password = sha666($('#password').val());
    var vcode = $('#vcode').val();

    // if (!/^\d{6}$/.test(vcode)) {
    //   $('#errorMsg').text('验证码格式不正确');
    //   return;
    // }

    loginHanlder(name, password, vcode);

  });

  // 实际登录操作
  function loginHanlder(name, password, vcode) {
    // 提交登录信息
    $.ajax(ajaxURL.SYSTEM + '/sys/user/sysUserlogin', {
      type: 'POST',
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
      data: {
        account: name,
        passWord: password,
        code: vcode || '1234'
      },
      success: function (res) {
        if (res.code === 0 || res.code === '0' || res.code === '200') {
          // 登录成功
          if ($check && $check.checked) {
            // 设置 cookie，保存用户名。path 置空表示该 cookie 只对当前页面有效
            Cookies.set(userName, name, { expires: expires, path: '' });
          } else {
            // 如果不记住，则删除该 cookie
            Cookies.remove(userName, { path: '' });
          }

          layer.load(1, { shade: [0.1, '#fff'] });

          var data = res.data;
          var userData = {
            loginName: name,
            userId: data.kid,
            name: data.name,
            account: data.account,
            phone: data.phone,
            token: data.token,
            time: $.now()
          };

          // 存储用户缓存信息
          localStorage.user = JSON.stringify(userData);

          setTimeout(function () {
            window.location.href = '/?from=login';
          }, 500);

        } else {
          errHandler(res.msg || '登录错误，请重试');
        }
      },
      error: function (xhr) {
        var result = xhr.responseText;
        var msgError = result && JSON.parse(result).error;
        if (msgError) {
          errHandler(msgError);
        }
      }
    });
  }

  function errHandler(errText) {
    var errCount = +localStorage.CUR_ERROR;
    if (errCount) {
      errCount++;
    } else {
      errCount = 1;
    }

    localStorage.CUR_ERROR = errCount;

    if (errCount >= MAX_ERROR) {
      errText = textLock;
      localStorage.LOGIN_LOCK = Date.now();
    }

    $('#errorMsg').text(errText);
  }

})(window, jQuery);
